import { Injectable } from '@angular/core';
import { NavParams, Events } from 'ionic-angular';
import { Http, Headers } from '@angular/http';
import { Storage } from '@ionic/storage';
import { AppConfig } from "../app/app.config";
import 'rxjs/Rx';

import { HelperService } from "./services.helper";
import { GlobalData } from '../providers/GlobalData';
import { LoginPage } from '../pages/login/login';
import { OfflineService } from "../providers/services.offline";

@Injectable()
export class ApiService {

    constructor(private http: Http,
        private storage: Storage,
        private events: Events,
        private global: GlobalData,
        private offline: OfflineService,
        private helperService: HelperService) {

    }

    getUrl(isActivate) {
        return new Promise<string>(resolve => {
            this.storage.get('activate').then(activate => {
                let url: string;
                if (isActivate) {
                    url = AppConfig.getServerHttp() +
                        activate.path +
                        AppConfig.getSubDomin() +
                        AppConfig.getApiPath();
                } else {
                    if (this.global.curEnvir == 'SANDBOX_MODE') {
                        url = AppConfig.getServerHttp() +
                            activate.prefix +
                            activate.path +
                            AppConfig.getSubDomin() +
                            AppConfig.getApiPath();
                    } else {
                        url = AppConfig.getServerHttp() +
                            activate.path +
                            AppConfig.getSubDomin() +
                            AppConfig.getApiPath();
                    }
                }
                console.log(url);
                resolve(url);
            });
        });
    }

    checkError(error): void {
        console.log('checkError:', error);
        if (error == 'Access denined.' || error == '权限拒绝。' || error == '權限拒絕。') {
            // access denined, log out & change status
            this.storage.get('user').then(user => {
                user.isLogin = false;
                this.storage.set('user', user);
                console.log('publish access_denined');
                this.events.publish('access_denined', Date.now());
            });
        }
    }

    activation(body) {
        this.helperService.showLoading();
        console.log('body', body);
        return new Promise((resolve, reject) => {
            this.getUrl(true).then(url => {
                console.log('url' + url);
                let uri = encodeURI(url);
                let headers = new Headers();
                headers.append('Content-Type', 'application/x-www-form-urlencoded');
                this.http.post(uri + "/activation", body.toString(), {
                    headers: headers
                }).map(res => res.json())
                    .subscribe(data => {
                        console.log('data', data);
                        if (data.status == 'Y') {
                            this.storage.set('activate', {
                                status: true,
                                path: body.get('app_name'),
                                prefix: 'sandbox.',
                                passcode: body.get('app_id'),
                                shop_icon: data.shop_icon
                            });
                            this.helperService.hideLoading();
                            resolve(data);

                        } else {
                            this.helperService.hideLoading();
                            reject(data.msg);
                        }
                    }, (err) => {
                        this.helperService.hideLoading();
                        reject(err);
                    });
            });
        });
    }

    auth(body) {
        return new Promise((resolve, reject) => {
            this.getUrl(false).then(url => {
                let uri = encodeURI(url);
                let headers = new Headers();
                headers.append('Content-Type', 'application/x-www-form-urlencoded');
                this.http.post(uri + "/auth", body, {
                    headers: headers
                }).map(res => res.json())
                    .subscribe(data => {
                        if (data.status == 'Y') {
                            resolve(data);
                        } else {
                            reject(data.msg);
                        }
                    }, (err) => {
                        reject(err);
                    });
            });
        });
    }

    login(body) {
        return new Promise((resolve, reject) => {
            this.getUrl(false).then(url => {
                let uri = encodeURI(url);
                let headers = new Headers();
                headers.append('Content-Type', 'application/x-www-form-urlencoded');
                this.http.post(uri + "/login", body, {
                    headers: headers
                }).map(res => res.json())
                    .subscribe(data => {
                        if (data.status == 'Y') {
                            resolve(data);
                        } else {
                            reject(data.msg);
                        }
                    }, (err) => {
                        reject(err);
                    });
            });
        });
    }

    settings(body) {
        return new Promise((resolve, reject) => {
            this.getUrl(false).then(url => {
                let uri = encodeURI(url);
                let headers = new Headers();
                headers.append('Content-Type', 'application/x-www-form-urlencoded');
                this.http.post(uri + "/settings", body, {
                    headers: headers
                }).map(res => res.json())
                    .subscribe(data => {
                        if (data.status == 'Y') {
                            resolve(data);
                        } else {
                            this.checkError(data.msg);
                            reject(data.msg);
                        }
                    }, (err) => {
                        reject(err);
                    });
            });
        });
    }

    getCategory(body) {
        return new Promise((resolve, reject) => {
            if (this.global.curMode == 'ONLINE_MODE') {
                this.getUrl(false).then(url => {
                    let uri = encodeURI(url);
                    let headers = new Headers();
                    headers.append('Content-Type', 'application/x-www-form-urlencoded');
                    this.http.post(uri + "/get-category", body, {
                        headers: headers
                    }).map(res => res.json())
                        .subscribe(data => {
                            if (data.status == 'Y') {
                                resolve(data);
                            } else {
                                this.checkError(data.msg);
                                reject(data.msg);
                            }
                        }, err => {
                            reject(err);
                        });
                });
            } else {
                this.offline.getCategory(body).then(data => {
                    resolve(data);
                }, err => {
                    reject(err);
                });
            }
        });
    }

    getProductList(body) {
        this.helperService.showLoading();
        return new Promise((resolve, reject) => {
            if (this.global.curMode == 'ONLINE_MODE') {
                this.getUrl(false).then(url => {
                    let uri = encodeURI(url);
                    let headers = new Headers();
                    headers.append('Content-Type', 'application/x-www-form-urlencoded');
                    this.http.post(uri + "/get-product-list", body, {
                        headers: headers
                    }).map(res => res.json())
                        .subscribe(data => {
                            if (data.status == 'Y') {
                                this.helperService.hideLoading();
                                resolve(data);
                            } else {
                                this.helperService.hideLoading();
                                this.checkError(data.msg);
                                reject(data.msg);
                            }
                        }, (err) => {
                            this.helperService.hideLoading();
                            reject(err);
                        });
                });
            } else {
                this.offline.getProductList(body).then(data => {
                    this.helperService.hideLoading();
                    resolve(data);
                }, err => {
                    this.helperService.hideLoading();
                    reject(err);
                });
            }
        });
    }

    getServingList(body) {
        return new Promise((resolve, reject) => {
            if (this.global.curMode == 'ONLINE_MODE') {
                this.getUrl(false).then(url => {
                    let uri = encodeURI(url);
                    let headers = new Headers();
                    headers.append('Content-Type', 'application/x-www-form-urlencoded');
                    this.http.post(uri + "/get-invoice-list-fab", body, {
                        headers: headers
                    }).map(res => res.json())
                        .subscribe(data => {
                            if (data.status == 'Y') {
                                resolve(data);
                            } else {
                                this.checkError(data.msg);
                                reject(data.msg);
                            }
                        }, (err) => {
                            reject(err);
                        });
                });
            } else {
                this.offline.getInvoiceList(body).then(data => {
                    resolve(data);
                }, err => {
                    reject(err);
                });
            }
        });
    }

    newCart(body) {
        return new Promise((resolve, reject) => {
            if (this.global.curMode == 'ONLINE_MODE') {
                this.getUrl(false).then(url => {
                    let uri = encodeURI(url);
                    let headers = new Headers();
                    headers.append('Content-Type', 'application/x-www-form-urlencoded');
                    this.http.post(uri + "/new-cart-fab", body, {
                        headers: headers
                    }).map(res => res.json())
                        .subscribe(data => {
                            if (data.status == 'Y') {
                                resolve(data);
                            } else {
                                this.checkError(data.msg);
                                reject(data.msg);
                            }
                        }, (err) => {
                            reject(err);
                        });
                });
            } else {
                this.offline.newCart(body).then(data => {
                    resolve(data);
                }, err => {
                    reject(err);
                });
            }
        });
    }

    setCart(body) {
        return new Promise((resolve, reject) => {
            if (this.global.curMode == 'ONLINE_MODE') {
                this.getUrl(false).then(url => {
                    let uri = encodeURI(url);
                    let headers = new Headers();
                    headers.append('Content-Type', 'application/x-www-form-urlencoded');
                    this.http.post(uri + "/set-cart-fab", body, {
                        headers: headers
                    }).map(res => res.json())
                        .subscribe(data => {
                            if (data.status == 'Y') {
                                resolve(data);
                            } else {
                                this.checkError(data.msg);
                                reject(data.msg);
                            }
                        }, (err) => {
                            reject(err);
                        });
                });
            } else {
                this.offline.setCart(body).then(data => {
                    resolve(data);
                }, err => {
                    reject(err);
                });
            }
        });
    }

    checkOut(body) {
        return new Promise((resolve, reject) => {
            if (this.global.curMode == 'ONLINE_MODE') {
                this.getUrl(false).then(url => {
                    let uri = encodeURI(url);
                    let headers = new Headers();
                    headers.append('Content-Type', 'application/x-www-form-urlencoded');
                    this.http.post(uri + "/checkout-fab", body, {
                        headers: headers
                    }).map(res => res.json())
                        .subscribe(data => {
                            if (data.status == 'Y') {
                                resolve(data);
                            } else {
                                this.checkError(data.msg);
                                reject(data.msg);
                            }
                        }, (err) => {
                            reject(err);
                        });
                });
            } else {
                this.offline.setCart(body).then(data => {
                    resolve(data);
                }, err => {
                    reject(err);
                });
            }
        });
    }

    getTableInfo(body) {
        return new Promise((resolve, reject) => {
            if (this.global.curMode == 'ONLINE_MODE') {
                this.getUrl(false).then(url => {
                    let uri = encodeURI(url);
                    let headers = new Headers();
                    headers.append('Content-Type', 'application/x-www-form-urlencoded');
                    this.http.post(uri + "/get-table-info", body, {
                        headers: headers
                    }).map(res => res.json())
                        .subscribe(data => {
                            if (data.status == 'Y') {
                                resolve(data);
                            } else {
                                this.checkError(data.msg);
                                reject(data.msg);
                            }
                        }, (err) => {
                            reject(err);
                        });
                });
            } else {
                this.offline.setCart(body).then(data => {
                    resolve(data);
                }, err => {
                    reject(err);
                });
            }
        });
    }

}
